
## Deficit Numbers in Introduction

#This code produces the deficits and percent changes used in the introduction 

library(dplyr)
library(ggplot2)

if(length(tryCatch(list.dirs(path="~/Library/CloudStorage/Dropbox/Robots and Trade in Services"),error=function(e) e))==0){
  base.path<-"~/Dropbox/Robots and Trade in Services/"
} else {
  base.path<-"~/Library/CloudStorage/Dropbox/Robots and Trade in Services/"
}

paths<-list.files(paste0(base.path,"Data/COMTRADE/Trade in Automation 10012022"),full.names = TRUE)

df<-bind_rows(lapply(paths,function(x) read.csv(x))) %>%
  #Processing
  mutate(commodity.type=ifelse(Commodity.Code=="TOTAL","TOTAL","Automation")) %>%
  group_by(Year,Trade.Flow,Reporter.ISO,Reporter,commodity.type) %>%
  summarize(value=sum(Trade.Value..US..,na.rm=TRUE)) %>%
  ungroup() %>%
  reshape2::dcast(Year+Reporter.ISO+Reporter ~ commodity.type + Trade.Flow,value.var="value")

spell_out<-function(num,latex_num=TRUE){
  #Objective: convert numeric to text, give one decimal when relatively small 
  
  #First get the order of magnitude
  fct<-log10(abs(num))
  
  #Small numbers are immediately returned
  if(fct<3){
    return(as.character(num))
  }
  
  #We have to stop at some point
  if(fct>=15){
    stop("Number out of range")
  }
  
  #Get the string for the end
  num_string<-case_when(
    fct>=3 & fct<6 ~ "thousand",
    fct>=6 & fct<9 ~ "million",
    fct>=9 & fct<12 ~ "billion",
    fct >=12 & fct<15 ~ "trillion"
  )
  
  #Get the leading number
  #Floor function gets the order of magnitude right, the rounding gives one decimal when the number is less than 10
  num_start<-round(num/10^(floor(fct/3)*3),ifelse(fct %% 3<=1,1,0))
  
  if(latex_num==TRUE){
    paste0("$",num_start,"$"," ",num_string)
  } else{
    paste0(num_start," ",num_string)
  }
  
}

#These numbers appear in the text
us.deficit.1991<-df %>% 
  filter(Reporter.ISO=="USA") %>%
  select(Year,contains("Automation")) %>%
  mutate(deficit=Automation_Export-Automation_Import) %>%
  .[.$Year=="1991","deficit"]

#These numbers appear in the text
us.deficit.2020<-df %>% 
  filter(Reporter.ISO=="USA") %>%
  select(Year,contains("Automation")) %>%
  mutate(deficit=Automation_Export-Automation_Import) %>%
  .[.$Year=="2020","deficit"]

#Calculate Deficit Percent Changes

deficit<-df %>% 
  filter(Reporter.ISO=="USA") %>%
  select(Year, Automation_Export,Automation_Import,TOTAL_Export,TOTAL_Import) %>%
  filter(Year==min(Year,na.rm=TRUE) | Year==max(Year,na.rm=TRUE)) %>%
  mutate(
    net_automation_exports=Automation_Export-Automation_Import,
    net_exports=TOTAL_Export-TOTAL_Import,
    net_automation_exports_diff=diff(net_automation_exports),
    net_exports_diff=diff(net_exports),
    net_automation_exports_change=net_automation_exports_diff/net_automation_exports,
    net_exports_change=net_exports_diff/net_exports,
  ) %>%
  filter(Year==min(Year,na.rm=TRUE)) %>%
  select(net_automation_exports_change,net_exports_change)
